#define _XOPEN_SOURCE 500

#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>

char *makemsg(char f[])
{
  char		       *msg;
  size_t		s_file;
  s_file = strlen(f);
  msg = malloc(s_file + 8);
  strncpy(msg,"myseek: ",8);
  strncat(msg,f,s_file);
  return msg;
}

int main (int argc, char* argv[])
{
	int fd;
	char* buf[1];
	
	if(argc == 2  && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")))
  {
    write(STDOUT_FILENO,"Usage : ",8);
   	write(STDOUT_FILENO, argv[0],strlen(argv[0]));
   	write(STDOUT_FILENO," file c",7);
    return (0);
  }
	
	if (argc < 3)
	{
		write(STDERR_FILENO,"Missing parameters\nUsage : ",28);
   	write(STDERR_FILENO, argv[0],strlen(argv[0]));
   	write(STDERR_FILENO," file c",7);
    exit(1);
	}
	
	if((fd = open (argv[1],O_RDONLY)) == -1)
	{
		perror (makemsg(argv[1]));
		exit (2);
	}

	if (lseek(fd, (argv[2][0] - 'a'), SEEK_SET) == -1)
	{
		perror (makemsg(&argv[2][0]));
	  exit (3);
	}
	
	while (read(fd, buf, 1) == -1)
	{
		if ( errno == EINTR || errno == EAGAIN )
	    continue;
	  perror (makemsg(argv[1]));
	  exit (4);
	}
	
	write (STDOUT_FILENO, buf, 1);
	
	close (fd);
	
	return 0;
}
